﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net.Sockets;
using App1AppHandler;
using System.Timers;
using Reborn_WorldServer.App1AppHandler;

namespace Reborn_WorldServer
{
    public class ClientSocketData
    {
        public SocketController socket;

        public byte[] dataBuffer = new byte[1024];

        public Character _character;

        //Flag gets set once the character has successfully entered the game (having issues with characters only have entering?
        //user ID appears to get set but the rest of the character data is missing, not sure how this is happening)
        public bool succesfullyEntered = false;

        private Timer connectionTimeout = new Timer(10000);

        public string clientId = "";

        public ClientSocketData(Socket clientSocket)
        {
            socket = new SocketController(clientSocket, this);
            connectionTimeout.Elapsed += new ElapsedEventHandler(connectionTimeout_Elapsed);
            connectionTimeout.AutoReset = false;
            connectionTimeout.Start();
        }
        public void killTimeout()
        {
            try
            {
                connectionTimeout.Stop();
                connectionTimeout.Dispose();
            }
            catch { }
        }
        private void connectionTimeout_Elapsed(object sender, ElapsedEventArgs e)
        {
            socket.Close();
        }

        private string incomingMessages = "";
        public void AppendData(string e)
        {
            lock (messageLock)
            {
                incomingMessages = incomingMessages + e;
            }
        }

        private object messageLock = new object();
        public string getMessage()
        {
            lock (messageLock)
            {
                if (incomingMessages.IndexOf("\0") > -1)
                {
                    string message = incomingMessages.Substring(0, incomingMessages.IndexOf("\0"));
                    incomingMessages = incomingMessages.Substring(incomingMessages.IndexOf("\0") + 1);
                    return message;
                }
                else
                    return "";
            }
        }
    }
}
